package primitive;

import primitive.Arena.Bot;

public class LeoBot extends Bot {
	public LeoBot(Arena arena) {
		arena.super();
	}
	private int direction=Arena.RIGHT;
	private int y,x;
	private char[][] map;
	private int nAlive,nGrenade;
	private boolean radar; 
	
	private int randDirection(){
		return 2*(int) (1+Math.floor(Math.random()*4));
	}
	
	public void main(String[] args){
		direction=randDirection();
	}

	public void run(){
		y = super.getY();
		x = super.getX();
		map = super.getVisible();
		nAlive = super.getNAlive();
		radar = super.hasRadar();
		nGrenade = super.getNGrenade();
		
		/*for(int i=0;i<map.length;i++){
			for(int j=0;j<map[i].length;j++){
				System.out.print(map[i][j]);
			}
			System.out.println();
		}*/
		
		// detect nearby enemies
		boolean enemies=false;
		for(int i=0;i<map.length;i++){
			for(int j=0;j<map[i].length;j++){
				if(map[i][j]>='A'&&map[i][j]<='D'&&!(i==3&&j==3)){
					enemies=true;
				}
			}
		}
		if(enemies){
			killEnemy();
			return;
		}
		
		
		// run towards edge
		boolean edge=false;
		for(int i=0;i<map.length;i++){
			for(int j=0;j<map[i].length;j++){
				if(map[i][j]=='O'){
					edge=true;
				}
			}
		}
		if(!edge){
			runTowardsEdge();
			return;
		}
		
		
		runTowardsEdge();
		
	}
	
	
	private void killEnemy(){
		// Immediately killable
		for(int i=0;i<map.length;i++){
			for(int j=0;j<map[i].length;j++){
				if(map[i][j]>='A'&&map[i][j]<='D'&&!(i==3&&j==3)){
					if(i==3 && Math.abs(j-3)<=1){
						if(j<x){
							super.shoot(Arena.LEFT);
							return;
						}else{
							super.shoot(Arena.RIGHT);
							return;
						}
					}
					if(j==3 && Math.abs(i-3)<=1){
						if(i<y){
							super.shoot(Arena.UP);
							return;
						}else{
							super.shoot(Arena.DOWN);
							return;
						}
					}
				}
			}
		}
		
		// If not
		for(int i=0;i<map.length;i++){
			for(int j=0;j<map[i].length;j++){
				if(map[i][j]>='A'&&map[i][j]<='D'&&!(i==3&&j==3)){
					if(Math.random()>0.5){
						if(i<3){
							super.move(Arena.UP);
							return;
						}
						else {
							super.move(Arena.DOWN);
							return;
						}
					}else{
						if(j<3){
							super.move(Arena.LEFT);
							return;
						}
						else {
							super.move(Arena.RIGHT);
							return;
						}
					}
				}
			}
		}
	}
	
	
	private void runTowardsEdge() {
		for (int n = 0; n < 8; n++) {
			int i = 3;
			int j = 3;
			switch (direction) {
			case Arena.UP:
				i--;
				break;
			case Arena.DOWN:
				i++;
				break;
			case Arena.LEFT:
				j--;
				break;
			case Arena.RIGHT:
				j++;
				break;
			}
			if (map[i][j] == '_') {
				super.move(direction);
				return;
			}
			if (map[i][j] == '#') {
				super.shoot(direction);
				return;
			}
			direction = randDirection();
		}
		super.move(direction);
		return;
	}
}
